﻿namespace TianYu.Core.Common
{
    /// <summary>通用返回信息类</summary>
    public class MessageModel<T>
    {
        /// <summary>错误信息</summary>
        public Dictionary<string, List<string>> errors { get; set; }

        /// <summary>状态码</summary>
        public MessageModelStatusCode status { get; set; } = MessageModelStatusCode.Code200;

        /// <summary>操作是否成功</summary>
        public bool success { get; set; } = false;

        /// <summary>返回信息</summary>
        public string msg { get; set; } = "";

        /// <summary>返回数据集合</summary>
        public T data { get; set; }

        /// <summary>返回成功</summary>
        /// <param name="response">需要返回的数据</param>
        /// <param name="msg">消息</param>
        /// <returns></returns>
        public static MessageModel<T> Success(T response = default, string msg = "success")
        {
            return Message(true, msg, response);
        }

        /// <summary>返回失败</summary>
        /// <param name="msg">消息</param>
        /// <param name="response">数据</param>
        /// <returns></returns>
        public static MessageModel<T> Fail(string msg, T response = default)
        {
            return Message(false, msg, response);
        }

        /// <summary>返回消息</summary>
        /// <param name="success">失败/成功</param>
        /// <param name="msg">消息</param>
        /// <param name="response">数据</param>
        /// <returns></returns>
        public static MessageModel<T> Message(bool success, string msg, T response)
        {
            return new MessageModel<T>() { msg = msg, data = response, success = success };
        }
    }

    public static class MessageModelExtensions
    {
        public static MessageModel<T> ToViewModel<T>(this T @this, string msg = "success", bool success = true, MessageModelStatusCode status = MessageModelStatusCode.Code200)
        {
            if (@this is bool value)
            {
                if (!value)
                {
                    throw new Exception("保存失败");
                }
            }

            return new MessageModel<T>() { status = status, data = @this, msg = msg, success = success };
        }
    }
}
